import { getContext } from '@/context/common/applicationContext'
import React, { Component } from 'react'
import { Drawer, Tabs, List, Modal, message } from 'antd'
import { TableButton } from '@/components/basicWidget/Button'
import { _delete, post } from '@/utils/requestUtil'
import { DeleteOutlined } from '@ant-design/icons'

class MessageDrawer extends Component {

    constructor(props) {
        super(props)
        this.state = {
            activeKey: '1',
            modalVisual: false, //消息详情显隐
            messageDetail: {}, //消息详情所展示的消息的id
        }
    }

    tabChange = async (key) => {
        await new Promise(resolve => {
            this.setState({ activeKey: key }, resolve)
        })
    }

    //未读页面
    renderUnreadPage = () => {
        return (
            <List
                itemLayout="horizontal"
                dataSource={this.props.userMessage.unreadMessage}
                header={
                    <div style={{ display: 'flex', flexDirection: 'row-reverse' }}>
                        <TableButton
                            onClick={async () => {
                                const ids = (this.props.userMessage.unreadMessage || []).map(item => item.id)
                                if (Array.isArray(ids) && ids.length > 0) {
                                    const response = await post('/message/read', {
                                        body: JSON.stringify(ids)
                                    })
                                    if (response && response.code === 200) {
                                        message.success('操作成功')
                                        await this.props.updateUserMessage()
                                    } else {
                                        message.warning('操作失败，请联系管理员')
                                    }
                                }
                            }}
                        >
                            全部已读
                        </TableButton>
                    </div>
                }
                renderItem={(item) => (
                    <List.Item
                        actions={[<span style={{ cursor: 'pointer' }} onClick={this.openMessageDetail(item)}>查看详情</span>]}
                    >
                        <List.Item.Meta
                            title={item.messageTitle}
                            description={item.sendTime}
                        />
                        {item.messageContent && item.messageContent.length > 100 ?
                            item.messageContent.substring(0, 100) + '...' : item.messageContent}
                    </List.Item>
                )}
            >
            </List>
        )
    }

    //已读页面
    renderReadPage = () => {
        return (
            <List
                itemLayout="horizontal"
                dataSource={this.props.userMessage.readMessage}
                header={
                    <div style={{ display: 'flex', flexDirection: 'row-reverse' }}>
                        <TableButton
                            style={{ backgroundColor: 'var(--bg-three-color)' }}
                            onClick={async () => {
                                const ids = (this.props.userMessage.readMessage || []).map(item => item.id)
                                if (Array.isArray(ids) && ids.length > 0) {
                                    await this.deleteMessage(ids)
                                }
                            }}
                        >
                            全部删除
                        </TableButton>
                    </div>
                }
                renderItem={(item) => (
                    <List.Item
                        actions={[<span style={{ cursor: 'pointer' }} onClick={this.openMessageDetail(item)}>查看详情</span>]}
                    >
                        <List.Item.Meta
                            title={item.messageTitle}
                            description={item.sendTime}
                        />
                        {item.messageContent && item.messageContent.length > 100 ?
                            item.messageContent.substring(0, 100) + '...' : item.messageContent}
                    </List.Item>
                )}
            >
            </List>
        )
    }

    openMessageDetail = (messageDetail) => {
        return async () => {
            await new Promise(resolve => {
                this.setState({
                    messageDetail,
                    modalVisual: true
                }, resolve)
            })
            if (messageDetail.messageStatus === 'unread') {
                //将消息置为已读状态
                await post('/message/read', {
                    body: JSON.stringify([messageDetail.id])
                })
                //更新消息
                await this.props.updateUserMessage()
            }
        }
    }

    modalCancel = async () => {
        await new Promise(resolve => {
            this.setState({
                messageDetail: {},
                modalVisual: false
            }, resolve)
        })
    }

    renderMessageDetail = () => {
        const { messageDetail } = this.state
        return (
            <Modal
                title={messageDetail.messageTitle}
                open={this.state.modalVisual}
                onCancel={this.modalCancel}
                footer={null}
                width={'60%'}
            >
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                    <span style={{ color: 'var(--one-font-color)', marginBottom: '20px' }}>{messageDetail.sendTime}</span>
                    <span style={{ maxHeight: '600px', overflow: 'auto' }}>{messageDetail.messageContent}</span>
                    <span style={{ marginTop: '20px' }}>
                        <span
                            style={{ cursor: 'pointer', color: 'var(--danger-font-color)' }}
                            onClick={async () => {
                                await this.deleteMessage([messageDetail.id])
                                await this.modalCancel()
                            }}
                        ><DeleteOutlined />删除
                        </span>
                    </span>
                </div>
            </Modal>
        )
    }

    /**
     * 删除消息
     * @param {Array} ids 消息id 
     */
    deleteMessage = async (ids) => {
        const response = await _delete('/message/delete', {
            body: JSON.stringify(ids)
        })
        if (response && response.code === 200) {
            message.success('消息删除成功')
            await this.props.updateUserMessage()
        } else {
            message.warning('操作失败，请联系管理员')
        }
    }

    render() {
        const tabItems = [
            {
                label: '未读',
                key: '1',
                children: this.renderUnreadPage()
            },
            {
                label: '已读',
                key: '2',
                children: this.renderReadPage()
            }
        ]
        return (
            <>
                <Drawer
                    closable={false}
                    width={720}
                    onClose={this.props.onClose}
                    open={this.props.drawerVisual}
                >
                    <Tabs
                        activeKey={this.state.activeKey}
                        items={tabItems}
                        onChange={this.tabChange}
                    ></Tabs>
                </Drawer>
                {this.renderMessageDetail()}
            </>
        )
    }
}
export default getContext(MessageDrawer)
